const axios = require('axios');
const ApiKeyService = require('./apiKeyService');
require('dotenv').config();

// 调用第三方AI API
async function callAIProvider(ai_role_id, input, type, systemPrompt = '', aiRoleConfig = null) {
  try {
    // 获取AI角色配置信息
    if (!aiRoleConfig) {
      // 如果未传入配置，则需要查询数据库获取
      const { AIRole } = require('../models');
      aiRoleConfig = await AIRole.findByPk(ai_role_id);
      if (!aiRoleConfig) {
        throw new Error('AI角色不存在');
      }
    }

    // 提取API提供商和配置
    const provider = aiRoleConfig.api_provider;
    const config = aiRoleConfig.api_config || {};

    let response;

    switch (type) {
      case 'text':
        response = await generateTextResponse(input, systemPrompt, provider, config);
        break;
      case 'voice':
        response = await generateVoiceResponse(input, systemPrompt, provider, config);
        break;
      case 'image':
        response = await generateImageResponse(input, systemPrompt, provider, config);
        break;
      default:
        response = `不支持的交互类型: ${type}`;
    }

    return response;
  } catch (error) {
    console.error('调用AI服务失败:', error);
    return '抱歉，AI服务暂时不可用，错误信息：' + error.message;
  }
}

// 生成文本响应
async function generateTextResponse(input, systemPrompt, provider, config) {
  try {
    switch (provider.toLowerCase()) {
      case 'openai':
        return await callOpenAI(input, systemPrompt, config);
      case 'deepseek':
        return await callDeepSeek(input, systemPrompt, config);
      case 'volcengine':
      case 'doubao':
        return await callVolcengine(input, systemPrompt, config);
      case 'azure':
        return await callAzureOpenAI(input, systemPrompt, config);
      case 'anthropic':
        return await callAnthropic(input, systemPrompt, config);
      case 'gemini':
        return await callGemini(input, systemPrompt, config);
      case 'custom':
      default:
        console.log(`使用模拟响应模式: ${provider}`);
        return `这是一个模拟的AI响应 (${provider}): ${input.substring(0, 20)}...`;
    }
  } catch (error) {
    console.error(`${provider} API调用失败:`, error);
    throw new Error(`${provider} API调用失败: ${error.message}`);
  }
}

// 调用OpenAI API
async function callOpenAI(input, systemPrompt, config) {
  // 优先使用数据库中的API密钥，如果没有则使用环境变量
  let OPENAI_API_KEY = await ApiKeyService.getOpenAIKey();
  if (!OPENAI_API_KEY) {
    OPENAI_API_KEY = process.env.OPENAI_API_KEY;
  }

  if (!OPENAI_API_KEY) {
    throw new Error('缺少OpenAI API Key，请在数据库中配置或设置环境变量');
  }

  const model = config.model || 'gpt-3.5-turbo';
  const temperature = config.temperature || 0.7;
  const max_tokens = config.max_tokens || 800;

  try {
    const response = await axios.post('https://api.openai.com/v1/chat/completions', {
      model: model,
      messages: [
        { role: 'system', content: systemPrompt },
        { role: 'user', content: input }
      ],
      temperature: temperature,
      max_tokens: max_tokens
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${OPENAI_API_KEY}`
      }
    });

    return response.data.choices[0].message.content;
  } catch (error) {
    console.error('OpenAI API调用失败:', error.response?.data || error.message);
    throw new Error(`OpenAI API调用失败: ${error.response?.data?.error?.message || error.message}`);
  }
}

// 调用火山引擎 Doubao API
async function callVolcengine(input, systemPrompt, config) {
  // 优先使用数据库中的API密钥，如果没有则使用环境变量
  const VOLCENGINE_API_KEY = (await ApiKeyService.getKeyByProvider('volcengine')) || process.env.VOLCENGINE_API_KEY;
  if (!VOLCENGINE_API_KEY) {
    throw new Error('缺少Volcengine API Key，请在数据库中配置或设置环境变量 VOLCENGINE_API_KEY');
  }

  // 兼容自定义端点/模型
  const endpoint = (config && config.endpoint) || 'https://ark.cn-beijing.volces.com/api/v3/chat/completions';
  const model = (config && config.model) || 'doubao-pro-32k';
  const temperature = (config && (config.temperature ?? 0.7));
  const max_tokens = (config && config.max_tokens) || 800;
  const stream = !!(config && config.stream);

  try {
    const body = {
      model,
      messages: [
        { role: 'system', content: systemPrompt },
        { role: 'user', content: input }
      ],
      temperature,
      max_tokens,
      stream
    };

    const response = await axios.post(endpoint, body, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${VOLCENGINE_API_KEY}`
      }
    });

    // Doubao 返回格式与 OpenAI 兼容
    const content = response.data?.choices?.[0]?.message?.content;
    if (!content) {
      throw new Error('Volcengine API 返回结果为空');
    }
    return content;
  } catch (error) {
    console.error('Volcengine API调用失败:', error.response?.data || error.message);
    throw new Error(`Volcengine API调用失败: ${error.response?.data?.error?.message || error.message}`);
  }
}

// 调用DeepSeek API
async function callDeepSeek(input, systemPrompt, config) {
  // 优先使用数据库中的API密钥，如果没有则使用环境变量
  const DEEPSEEK_API_KEY = (await ApiKeyService.getKeyByProvider('deepseek')) || process.env.DeepSeek_API_Key;
  if (!DEEPSEEK_API_KEY) {
    throw new Error('缺少DeepSeek API Key，请在数据库中配置或设置环境变量');
  }

  const model = config.model || 'deepseek-chat';
  const temperature = config.temperature || 0.7;
  const max_tokens = config.max_tokens || 800;

  try {
    const response = await axios.post('https://api.deepseek.com/chat/completions', {
      model: model,
      messages: [
        { role: 'system', content: systemPrompt },
        { role: 'user', content: input }
      ],
      temperature: temperature,
      max_tokens: max_tokens,
      stream: false
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${DEEPSEEK_API_KEY}`
      }
    });

    return response.data.choices[0].message.content;
  } catch (error) {
    console.error('DeepSeek API调用失败:', error.response?.data || error.message);
    throw new Error(`DeepSeek API调用失败: ${error.response?.data?.error?.message || error.message}`);
  }
}

// 调用Azure OpenAI API
async function callAzureOpenAI(input, systemPrompt, config) {
  // 需要在.env配置Azure相关密钥和端点
  if (!config.endpoint || !config.api_key || !config.deployment_id) {
    throw new Error('缺少Azure配置信息');
  }

  try {
    const response = await axios.post(`${config.endpoint}/openai/deployments/${config.deployment_id}/chat/completions?api-version=${config.api_version || '2023-05-15'}`, {
      messages: [
        { role: 'system', content: systemPrompt },
        { role: 'user', content: input }
      ],
      temperature: config.temperature || 0.7,
      max_tokens: config.max_tokens || 800
    }, {
      headers: {
        'Content-Type': 'application/json',
        'api-key': config.api_key
      }
    });

    return response.data.choices[0].message.content;
  } catch (error) {
    console.error('Azure OpenAI API调用失败:', error.response?.data || error.message);
    throw new Error(`Azure OpenAI API调用失败: ${error.response?.data?.error?.message || error.message}`);
  }
}

// 调用Anthropic API (Claude)
async function callAnthropic(input, systemPrompt, config) {
  // 优先使用数据库中的API密钥，如果没有则使用环境变量
  let ANTHROPIC_API_KEY = await ApiKeyService.getClaudeKey();
  if (!ANTHROPIC_API_KEY) {
    ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;
  }

  if (!ANTHROPIC_API_KEY) {
    throw new Error('缺少Anthropic API Key，请在数据库中配置或设置环境变量');
  }

  const model = config.model || 'claude-2';
  const temperature = config.temperature || 0.7;
  const max_tokens = config.max_tokens || 1000;

  try {
    const response = await axios.post('https://api.anthropic.com/v1/messages', {
      model: model,
      system: systemPrompt,
      messages: [
        { role: 'user', content: input }
      ],
      temperature: temperature,
      max_tokens: max_tokens
    }, {
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': ANTHROPIC_API_KEY,
        'anthropic-version': '2023-06-01'
      }
    });

    return response.data.content[0].text;
  } catch (error) {
    console.error('Anthropic API调用失败:', error.response?.data || error.message);
    throw new Error(`Anthropic API调用失败: ${error.response?.data?.error?.message || error.message}`);
  }
}

// 调用Google Gemini API
async function callGemini(input, systemPrompt, config) {
  // 优先使用数据库中的API密钥，如果没有则使用环境变量
  let GEMINI_API_KEY = await ApiKeyService.getGeminiKey();
  if (!GEMINI_API_KEY) {
    GEMINI_API_KEY = process.env.GEMINI_API_KEY;
  }

  if (!GEMINI_API_KEY) {
    throw new Error('缺少Gemini API Key，请在数据库中配置或设置环境变量');
  }

  const model = config.model || 'gemini-pro';
  const temperature = config.temperature || 0.7;
  const max_output_tokens = config.max_output_tokens || 800;

  try {
    const response = await axios.post(`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${GEMINI_API_KEY}`, {
      contents: [
        {
          role: 'user',
          parts: [
            { text: `${systemPrompt}\n\n${input}` }
          ]
        }
      ],
      generationConfig: {
        temperature: temperature,
        maxOutputTokens: max_output_tokens
      }
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    });

    return response.data.candidates[0].content.parts[0].text;
  } catch (error) {
    console.error('Gemini API调用失败:', error.response?.data || error.message);
    throw new Error(`Gemini API调用失败: ${error.response?.data?.error?.message || error.message}`);
  }
}

// 语音生成 - 目前为模拟实现
async function generateVoiceResponse(input, systemPrompt, provider, config) {
  // 实际应用中应该调用语音合成API
  console.log(`[${provider}] 使用系统提示词进行语音生成: ${systemPrompt.substring(0, 30)}...`);

  // 先获取文本回复
  const textResponse = await generateTextResponse(input, systemPrompt, provider, config);

  return {
    type: 'voice',
    url: '/sample-voice-response.mp3', // 应替换为实际生成的语音URL
    text: textResponse
  };
}

// 图像生成 - 目前为模拟实现
async function generateImageResponse(input, systemPrompt, provider, config) {
  // 实际应用中应该调用图像生成API
  console.log(`[${provider}] 使用系统提示词进行图像生成: ${systemPrompt.substring(0, 30)}...`);

  return {
    type: 'image',
    url: '/sample-image-response.jpg', // 应替换为实际生成的图像URL
    description: `AI (${provider}) 生成的图像: ${input.substring(0, 20)}...`
  };
}

module.exports = callAIProvider;